package com.nba.dao.impl;

import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import com.nba.bean.Team;
import com.nba.bean.inherit.TeamInherit;
import com.nba.dao.TeamDao;
import com.nba.util.DBUtil;

public class TeamDaoImpl implements TeamDao {
	JdbcTemplate jt = new JdbcTemplate(DBUtil.getDataSource());
	
	@Override
	public List<Team> selectTeamAll() {
		String sql = "SELECT * FROM team";
		List<Team> list = jt.query(sql, new BeanPropertyRowMapper<Team>(Team.class));
		return list;
	}

	@Override
	public Team selectTeamById(int teamId) {
		String sql = "SELECT * FROM team WHERE team_id = ?";
		List<Team> list = jt.query(sql, new BeanPropertyRowMapper<Team>(Team.class),teamId);
		if(list.size() == 0) {
			return null;
		}else {
			return list.get(0);
		}
	}

	@Override
	public int deleteTeamById(int teamId) {
		String sql = "DELETE FROM team WHERE team_id = ?";
		return jt.update(sql,teamId);
	}


	@Override
	public int insertTeam(Team team) {
		String sql = "INSERT INTO team(team_name,team_region,team_url,team_coach,team_stadium,union_id,partition_id) Value(?,?,?,?,?,?,?)";
		return jt.update(sql, team.getTeamName(),team.getTeamRegion(),team.getTeamUrl(),team.getTeamCoach(),team.getTeamStadium(),team.getUnionId(),team.getPartitionId());
	}

	@Override
	public List<TeamInherit> selectTeam(String keyword,int pageNum, int pageSize) {
		String sql = "SELECT * FROM tup WHERE team_name LIKE ? OR team_region like ? OR team_coach like ? OR team_stadium like ? OR union_name like ? OR partition_name like ? LIMIT ?,?";
		return jt.query(sql, new BeanPropertyRowMapper<TeamInherit>(TeamInherit.class),"%"+keyword+"%","%"+keyword+"%","%"+keyword+"%","%"+keyword+"%","%"+keyword+"%","%"+keyword+"%",(pageNum-1)*pageSize,pageSize);
	}

	@Override
	public int selectTeamTotalRows(String keyword) {
		String sql = "SELECT count(1) FROM tup WHERE team_name LIKE ? OR team_region like ? OR team_coach like ? OR team_stadium like ? OR union_name like ? OR partition_name like ?";	
		return jt.queryForObject(sql, Integer.class,"%"+keyword+"%","%"+keyword+"%","%"+keyword+"%","%"+keyword+"%","%"+keyword+"%","%"+keyword+"%");
	}

	@Override
	public int updateTeam(Team team) {
		String sql = "UPDATE team SET team_name = ?,team_region = ?,team_url = ?,team_coach = ?,team_stadium = ?,union_id = ?,partition_id = ? WHERE team_id = ?";
		return jt.update(sql, team.getTeamName(),team.getTeamRegion(),team.getTeamUrl(),team.getTeamCoach(),team.getTeamStadium(),team.getUnionId(),team.getPartitionId(),team.getTeamId());
	}

	@Override
	public Team selectTeamByName(String teamName) {
		String sql = "SELECT * FROM team  WHERE team_name = ?";
		List<Team> list = jt.query(sql, new BeanPropertyRowMapper<Team>(Team.class),teamName);
		if(list.size() == 0) {
			return null;
		}else {
			return list.get(0);
		}
	}

}
